﻿using System;
using System.IO;
using System.Net;
using System.Text;
using System.Web;
using System.Web.Mvc;
using Azure.Online.Web.Utils;

namespace Azure.Online.Web.Models.Proxy {
    public class ProxyActionResult : ActionResult {
        private readonly HttpWebResponse _response;

        public ProxyActionResult(HttpWebResponse response) {
            _response = response;
        }

        public bool AcceptBase64 { get; set; }

        public override void ExecuteResult(ControllerContext context) {
            HttpResponseBase response = context.HttpContext.Response;
            response.StatusCode = (int)_response.StatusCode;
            response.StatusDescription = _response.StatusDescription;
            RegisterHeaders(response);

            var stream = _response.GetResponseStream();
            if (AcceptBase64) {
                var mem = new MemoryStream();
                stream.CopyTo(mem);
                var bytes = mem.ToArray();
                var content = Convert.ToBase64String(bytes);
                var output = Encoding.UTF8.GetBytes(content);
                response.Headers["Content-Length"] = output.Length.ToString();
                response.OutputStream.Write(output, 0, output.Length);
            } else {
                CopyHeader(response, "Content-Length");
                StreamUtils.CopyStream(stream, response.OutputStream);
            }
        }

        protected virtual void RegisterHeaders(HttpResponseBase response) {
            response.ContentType = _response.ContentType;
            foreach (string headerName in _response.Headers.Keys) {
                if (headerName.StartsWith("x-ms-")) {
                    CopyHeader(response, headerName);
                }
            }
        }

        private void CopyHeader(HttpResponseBase response, string headerName) {
            var value = _response.Headers[headerName];
            if (!string.IsNullOrEmpty(value)) {
                response.Headers[headerName] = value;
            }
        }


    }
}